package gw.com.android.ui.dialog;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ValueAnimator;
import android.app.Activity;
import android.app.Dialog;
import android.graphics.BitmapFactory;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.OvershootInterpolator;
import android.widget.ImageView;
import android.widget.TextView;

import com.gwtsz.gts2.hx.R;
import com.umeng.analytics.MobclickAgent;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.PlatformActionListener;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.tencent.qq.QQ;
import cn.sharesdk.wechat.friends.Wechat;
import cn.sharesdk.wechat.moments.WechatMoments;
import gw.com.android.app.AppContances;
import gw.com.android.app.AppMain;
import gw.com.android.app.GTConfig;
import gw.com.android.utils.ENV;
import gw.com.android.utils.ImageUtil;
import www.com.library.model.DataItemDetail;
import www.com.library.model.DataItemResult;
import www.com.library.util.DeviceUtil;
import www.com.library.view.RecyclerClickListener;

/**
 * Created by reeta.zou on 2016/10/8.
 * 分享弹层
 */
public class SharePopWindow {

    private Activity activity;
    private Dialog dialog;
    private RecyclerClickListener callback;

    private View dialogView;
    private ShareTypeAdapter modeListAdapter;

    private DataItemResult mResult;
    private int mShareType;
    private RecyclerView popListView;

    public SharePopWindow(Activity activity, int shareType, View view, DataItemDetail mItem, RecyclerClickListener callback) {
        this.mShareType = shareType;
        initDialog(activity, R.layout.dialog_share_pop_v, callback);
    }

    public SharePopWindow(Activity activity, int shareType, View view, DataItemDetail mItem, final ShareCallback callback) {
        this.mShareType = shareType;
        initDialog(activity, R.layout.dialog_share_pop, new RecyclerClickListener() {
            @Override
            public void onClick(int position, DataItemDetail itemDetail) {
                if (callback != null) {
                    callback.onClick(position, itemDetail, SharePopWindow.this);
                }
            }
        });
    }

    private void initDialog(Activity activity, int layoutId, RecyclerClickListener callback) {
        this.activity = activity;
        this.callback = callback;
        final LayoutInflater inflater = LayoutInflater.from(activity);
        dialogView = inflater.inflate(layoutId, null);

        createPopWindow(dialogView);
    }


    public SharePopWindow title(CharSequence text) {
        TextView tv = (TextView) dialogView.findViewById(R.id.share_title);
        tv.setGravity(Gravity.CENTER);
        tv.setTextSize(14);
        tv.setText(text);
        return this;
    }

    private void createPopWindow(View dialogView) {
        setArrayData();

        popListView = (RecyclerView) dialogView.findViewById(R.id.pop_list);
        layout_up = (ViewGroup) dialogView.findViewById(R.id.layout_up);
        modeListAdapter = new ShareTypeAdapter(activity);
        popListView.setAdapter(modeListAdapter);
        // 线性布局管理器
        GridLayoutManager layoutManager = new GridLayoutManager(activity, 4);
        // 设置布局管理器
        popListView.setLayoutManager(layoutManager);

        dialogView.findViewById(R.id.btn_cancel).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dismiss();
            }
        });

        dialog = new Dialog(activity, R.style.dialog_loading_bar_no_frame);
        dialog.setContentView(dialogView);
        dialog.setCanceledOnTouchOutside(true);
        dialog.setCancelable(true);
        Window window = dialog.getWindow();
        if (window != null) {
            WindowManager.LayoutParams params = window.getAttributes();
            params.gravity = Gravity.BOTTOM;
            params.width = DeviceUtil.instance().getScreenPixelsWidth(activity);
            window.setWindowAnimations(R.style.popwindow_anim_style);
        }

        //由于动画和listView添加元素是两个独立的过程， 所以可能在listView还没有准备就绪的时候，动画就开始了，如果这个时候动画开始，那么子元素将会没有动画效果
        //所以，必须加变量去控制子元素的动画启动时机
        popListView.addOnChildAttachStateChangeListener(new RecyclerView.OnChildAttachStateChangeListener() {
            @Override
            public void onChildViewAttachedToWindow(View view) {
                int c1 = popListView.getChildCount();
                if (c1 == mResult.getDataList().size()) {//如果所有的数据都已经转化成子view添加到了listView中
                    // 那就说明子元素的动画可以开始了
                    ifChildrenReady = true;
                    if (ifAnimatorStared && ifChildrenReady) {//执行动画有两个条件，1，动画就绪，2，子元素就绪，
                        // 如果动画先就绪，但是子元素没就绪，那么就会执行到这里，直到所有子元素都就绪了，才会进行动画
                        startChildAnim();
                    }
                }
            }

            @Override
            public void onChildViewDetachedFromWindow(View view) {
                int c2 = popListView.getChildCount();
                Log.d("onChildViewDetached", "" + c2);
            }
        });
    }

    private boolean ifAnimatorStared = false;// 动画flag已就绪，如果这个值是true，那就说明
    private boolean ifChildrenReady = false;

    /**
     * 设置界面分享类型数据
     */
    private void setArrayData() {
        mResult = new DataItemResult();

        DataItemDetail item = new DataItemDetail();
        item.setIntValue("title", R.string.app_share_wechat);
        item.setIntValue("iconID", R.mipmap.sns_weixin_icon);
        mResult.addItem(item);

        item = new DataItemDetail();
        item.setIntValue("title", R.string.app_share_wechat_friend);
        item.setIntValue("iconID", R.mipmap.sns_pyquan_icon);
        mResult.addItem(item);

        item = new DataItemDetail();
        item.setIntValue("title", R.string.app_share_qq);
        item.setIntValue("iconID", R.mipmap.sns_qq_icon);
        mResult.addItem(item);

        //最新设计图里面没有"复制链接"这一项，所以屏蔽
//        if (mShareType == AppContances.SHARE_ADS_TYPE) {
//            item = new DataItemDetail();
//            item.setIntValue("title", R.string.app_share_copy);
//            item.setIntValue("iconID", R.mipmap.sns_copylink_icon);
//            mResult.addItem(item);
//        }
    }

    public void show() {
        if (dialog == null || dialog.isShowing() || modeListAdapter.getItemCount() < 1) {
            return;
        }
        dialog.show();
        startAnimLayout();
        startChildAnim();
    }

    public void dismiss() {
        if (dialog != null && dialog.isShowing()) {
            dialog.dismiss();
        }
    }

    /**
     * 具体分享功能
     */
    public void onShareFun(int typeId, String title, String content, String mNewsUrl, PlatformActionListener listener) {
        onShareFun(typeId, title, content, mNewsUrl, "", listener);
    }

    /**
     * 具体分享功能
     */
    public void onShareFun(int typeId, String title, String content, String mNewsUrl, String imageUrl, PlatformActionListener listener) {

        if (typeId == R.string.app_share_wechat) {
            Wechat.ShareParams sp = new Wechat.ShareParams();
            sp.setTitle(title);
            sp.setText(content);
            sp.setUrl(mNewsUrl);// 标题的超链接
            if (mShareType == AppContances.SHARE_IMAGE_TYPE) {
                sp.setShareType(Platform.SHARE_IMAGE);
                sp.setImagePath(imageUrl);
            } else {
                sp.setShareType(Platform.SHARE_TEXT);
                sp.setShareType(Platform.SHARE_WEBPAGE);
                if (null != imageUrl && imageUrl.length() > 0) {
                    sp.setImageUrl(imageUrl);
                } else if (mShareType == AppContances.SHARE_RECOMMEND_TYPE) {
                    String path = GTConfig.instance().getRootDirectory() + "/share_logo.png";
                    ImageUtil.moveImage(BitmapFactory.decodeResource(AppMain.getApp().getResources(), R.mipmap.share_logo), path);
                    sp.setImagePath(path);
                    //sp.setImageData(BitmapFactory.decodeResource(AppMain.getApp().getResources(),R.mipmap.share_logo));// 分享网络图片
                } else if (mShareType == AppContances.SHARE_ADS_TYPE || mShareType == AppContances.SHARE_PROFIT_TYPE) {
                    String path = GTConfig.instance().getRootDirectory() + "/config.png";
                    ImageUtil.moveImage(BitmapFactory.decodeResource(AppMain.getApp().getResources(), ENV.getAppIcon(AppMain.getApp())), path);
                    sp.setImagePath(path);
                } else if (mShareType == AppContances.SHARE_ORDER_TYPE) {
                    String path = GTConfig.instance().getRootDirectory() + "/order_share.png";
                    ImageUtil.moveImage(BitmapFactory.decodeResource(AppMain.getApp().getResources(), R.mipmap.order_share), path);
                    sp.setImagePath(path);
                    MobclickAgent.onEvent(activity, "WXFriendsShare");
                }
            }
            Platform wechat = ShareSDK.getPlatform(Wechat.NAME);
            wechat.setPlatformActionListener(listener); // 设置分享事件回调
            // 执行分享
            wechat.share(sp);
        } else if (typeId == R.string.app_share_wechat_friend) {
            WechatMoments.ShareParams sp = new WechatMoments.ShareParams();
            sp.setTitle(title);
            sp.setText(content);
            sp.setUrl(mNewsUrl);// 标题的超链接
            if (mShareType == AppContances.SHARE_IMAGE_TYPE) {
                sp.setShareType(Platform.SHARE_IMAGE);
                sp.setImagePath(imageUrl);
            } else {
                sp.setShareType(Platform.SHARE_TEXT);
                sp.setShareType(Platform.SHARE_WEBPAGE);
                if (null != imageUrl && imageUrl.length() > 0) {
                    sp.setImageUrl(imageUrl);
                } else if (mShareType == AppContances.SHARE_RECOMMEND_TYPE) {
                    String path = GTConfig.instance().getRootDirectory() + "/share_logo.png";
                    ImageUtil.moveImage(BitmapFactory.decodeResource(AppMain.getApp().getResources(), R.mipmap.share_logo), path);
                    sp.setImagePath(path);
                    //sp.setImageData(BitmapFactory.decodeResource(AppMain.getApp().getResources(),R.mipmap.share_logo));// 分享网络图片
                } else if (mShareType == AppContances.SHARE_ADS_TYPE || mShareType == AppContances.SHARE_PROFIT_TYPE) {
                    String path = GTConfig.instance().getRootDirectory() + "/config.png";
                    ImageUtil.moveImage(BitmapFactory.decodeResource(AppMain.getApp().getResources(), ENV.getAppIcon(AppMain.getApp())), path);
                    sp.setImagePath(path);
                } else if (mShareType == AppContances.SHARE_ORDER_TYPE) {
                    String path = GTConfig.instance().getRootDirectory() + "/order_share.png";
                    ImageUtil.moveImage(BitmapFactory.decodeResource(AppMain.getApp().getResources(), R.mipmap.order_share), path);
                    sp.setImagePath(path);
                    MobclickAgent.onEvent(activity, "WXFriendsCircleShare");
                }
            }
            Platform wechatMoments = ShareSDK.getPlatform(WechatMoments.NAME);
            wechatMoments.setPlatformActionListener(listener); // 设置分享事件回调
            // 执行分享
            wechatMoments.share(sp);
        } else if (typeId == R.string.app_share_qq) {
            QQ.ShareParams sp = new QQ.ShareParams();
            sp.setTitle(title);
            sp.setText(content);
            sp.setTitleUrl(mNewsUrl); // 标题的超链接
            if (mShareType == AppContances.SHARE_IMAGE_TYPE) {
                sp.setShareType(Platform.SHARE_IMAGE);
                sp.setImagePath(imageUrl);
            } else {
                if (null != imageUrl && imageUrl.length() > 0) {
                    sp.setImageUrl(imageUrl);
                } else if (mShareType == AppContances.SHARE_RECOMMEND_TYPE) {
                    String path = GTConfig.instance().getRootDirectory() + "/share_logo.png";
                    ImageUtil.moveImage(BitmapFactory.decodeResource(AppMain.getApp().getResources(), R.mipmap.share_logo), path);
                    sp.setImagePath(path);
                } else if (mShareType == AppContances.SHARE_ADS_TYPE || mShareType == AppContances.SHARE_PROFIT_TYPE) {
                    String path = GTConfig.instance().getRootDirectory() + "/config.png";
                    ImageUtil.moveImage(BitmapFactory.decodeResource(AppMain.getApp().getResources(), ENV.getAppIcon(AppMain.getApp())), path);
                    sp.setImagePath(path);
                } else if (mShareType == AppContances.SHARE_ORDER_TYPE) {
                    String path = GTConfig.instance().getRootDirectory() + "/order_share.png";
                    ImageUtil.moveImage(BitmapFactory.decodeResource(AppMain.getApp().getResources(), R.mipmap.order_share), path);
                    sp.setImagePath(path);
                    MobclickAgent.onEvent(activity, "QQShare");
                }
            }
            Platform qq = ShareSDK.getPlatform(QQ.NAME);
            qq.setPlatformActionListener(listener); // 设置分享事件回调
            // 执行分享
            qq.share(sp);
        }
        dismiss();
    }


    /**
     * 根据位置返回文案id
     */
    public int getTitleId(int position) {
        return mResult.getItem(position).getInt("title");
    }


    /**
     * 分享类型列表适配器
     *
     * @author reeta
     */
    public class ShareTypeAdapter extends RecyclerView.Adapter {
        private LayoutInflater mInflater;

        ShareTypeAdapter(Activity act) {
            mInflater = LayoutInflater.from(act);
        }

        public DataItemDetail getItem(int position) {
            if (position < 0 || position >= mResult.getDataCount())
                return null;
            return mResult.getItem(position);
        }

        @Override
        public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            View itemView = mInflater.inflate(R.layout.list_item_share, null);
            return new ItemView(itemView);
        }

        @Override
        public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
            ItemView viewHold = (ItemView) holder;
            if (viewHold.mView != null) {
                DataItemDetail mItem = getItem(position);
                viewHold.mView.setText(AppMain.getAppString(mItem.getInt("title")));
                viewHold.mImageView.setImageResource(mItem.getInt("iconID"));
                viewHold.mView.setTag(position);
//                viewHold.mView.setAlpha(0);
            }
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public int getItemCount() {
            if (null != mResult) {
                return mResult.getDataCount();
            }
            return 0;
        }

        class ItemView extends RecyclerView.ViewHolder {

            @BindView(R.id.item_title)
            TextView mView;
            @BindView(R.id.item_image)
            ImageView mImageView;

            public ItemView(View itemView) {
                super(itemView);
                ButterKnife.bind(this, itemView);
            }

            @OnClick(R.id.item_layout)
            void onClick() {
                if (null != callback) {
                    int position = (int) mView.getTag();
                    callback.onClick(position, getItem(position));
                }
            }
        }
    }

    public interface ShareCallback {

        void onClick(int position, DataItemDetail itemDetail, SharePopWindow popWindow);

    }


    //=================新增的动画代码=====================、
    private int animDuration = 500;
    private ViewGroup layout_up;

    private void startAnimLayout() {
        //整体layout的动画，Y轴移动
        final int height = 50;//dialogView.getMeasuredHeight();
        final ValueAnimator anim = ValueAnimator.ofFloat(1, 0, 1);
        anim.setDuration(animDuration);
        anim.setInterpolator(new OvershootInterpolator());
        anim.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                float value = (float) animation.getAnimatedValue();
                layout_up.setTranslationY((1 - value) * height);
            }
        });
        anim.start();
    }

    private void startChildAnim() {

        ifAnimatorStared = true;
        int count = popListView.getChildCount();
        Log.d("getChildCount", "" + count);
        long delay = 0;

        for (int i = 0; i < count; i++) {
            final View child = popListView.getChildAt(i);
            child.setTranslationY(1 * 600);
            child.setAlpha(1 - 1);
        }

        for (int i = 0; i < count; i++) {
            final View child = popListView.getChildAt(i);

            ValueAnimator anim = ValueAnimator.ofFloat(1, 0);
            anim.setDuration(animDuration);
            anim.setInterpolator(new OvershootInterpolator());
            anim.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
                @Override
                public void onAnimationUpdate(ValueAnimator animation) {
                    float value = (float) animation.getAnimatedValue();
                    child.setTranslationY(value * 600);
                    child.setAlpha(1 - value);
                }
            });
            anim.setStartDelay(delay);
            anim.addListener(new AnimatorListenerAdapter() {
                @Override
                public void onAnimationEnd(Animator animation) {
                    ifAnimatorStared = false;
                    super.onAnimationEnd(animation);
                }

                @Override
                public void onAnimationStart(Animator animation) {
                    ifAnimatorStared = true;
                    super.onAnimationStart(animation);
                }
            });
            anim.start();
            delay += 100;
        }
    }
}
